/* eslint-disable no-console */
const { join } = require('node:path')
const { existsSync } = require('node:fs')

const inquirer = require('inquirer')
const { default: chalk } = require('chalk')
const download = require('download-git-repo')
const Spinnies = require('spinnies')
const semver = require('semver')

const pkg = require('../../package.json')
const question = require('../questions/downloadQ.js')

if (pkg.engines && !semver.satisfies(process.version, pkg.engines.node)) {
  console.log(chalk.bgRed(`Error: node 版本需${pkg.engines.node}`))
  process.exit(1)
}

inquirer.prompt(question)
  .then((anwser) => {
    const { model, name } = anwser
    const targetPath = join(__dirname, name)

    if (existsSync(targetPath)) {
      console.log(chalk.bgRed('Error: 文件已存在!'))
      process.exit(1)
    }

    const spinnies = new Spinnies()
    spinnies.add('spinner-1', { text: 'Downloading...' })

    new Promise((resolve, reject) => {
      // mkdirSync(targetPath)
      download(`direct:https://gitee.com/yangggjian/vue-template.git#${model}`, name, { clone: true }, (err) => {
        err ? reject(err) : resolve()
      })
    })
      .then(() => {
        spinnies.succeed('spinner-1', { text: 'Success!' })
      })
      .catch((err) => {
        // rmdirSync(targetPath)
        console.log(err)
      })
      .finally(() => {
        spinnies.remove('spinner-1')
      })
  })
